package com.bc.utils.network;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.SyncBasicHttpContext;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class HttpClient {
	private static final int DEFAULT_MAX_CONNECTIONS = 10;
	private static final int DEFAULT_SOCKET_TIMEOUT = 20 * 1000;
	private static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192;
	private static String PROXY_IP = "http://10.0.0.172:80";

	private static final DefaultHttpClient httpClient;
	private static HttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());

	static {
		BasicHttpParams httpParams = new BasicHttpParams();

		ConnManagerParams.setTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
		ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
		ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

		HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
		HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
		HttpConnectionParams.setTcpNoDelay(httpParams, true);
		HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

		HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setUserAgent(httpParams, "xiaoheiwu");

		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
		ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

		httpClient = new DefaultHttpClient(cm, httpParams);

	}

	private static String execute(HttpUriRequest httpRequest) throws IOException, ClientProtocolException,
			HttpResponseException {
		HttpResponse httpResponse = httpClient.execute(httpRequest, httpContext);
		StatusLine status = httpResponse.getStatusLine();
		String responseBody = null;
		HttpEntity entity = null;
		HttpEntity temp = httpResponse.getEntity();
		if (temp != null) {
			entity = new BufferedHttpEntity(temp);
			responseBody = EntityUtils.toString(entity, "UTF-8");
		}

		if (status.getStatusCode() >= 300) {
			throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
		}
		return responseBody;
	}

	public static String get(String url) throws ClientProtocolException, IOException {
		HttpUriRequest httpRequest = new HttpGet(url);
		return execute(httpRequest);
	}

	public static String get(String url, RequestParams params) throws HttpResponseException, ClientProtocolException,
			IOException {
		return get(getUrlWithQueryString(url, params));
	}

	public static String getViaCmwap(String url) throws IOException {
		URL targetUrl = new URL(url);
		URL proxyUrl = new URL(PROXY_IP + targetUrl.getPath()+"?"+targetUrl.getQuery());
		Log.i("网络连接", proxyUrl.toString());
		HttpURLConnection httpUrlConnection = (HttpURLConnection) proxyUrl.openConnection();

		httpUrlConnection.setRequestProperty("X-Online-Host", targetUrl.getHost() + ":" + targetUrl.getPort());
		httpUrlConnection.setRequestMethod("GET");
		httpUrlConnection.setRequestProperty("Accept", "text/html");
		httpUrlConnection.setRequestProperty("Pragma", "No-cache");
		httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
		httpUrlConnection.setRequestProperty("connection", "keep-alive");
		//httpUrlConnection.setRequestProperty("accept-charset", "utf-8");
		httpUrlConnection.setConnectTimeout(10 * 1000);

		if (httpUrlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
			throw new HttpResponseException(httpUrlConnection.getResponseCode(), httpUrlConnection.getResponseMessage());
		}

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		BufferedInputStream input = new BufferedInputStream(httpUrlConnection.getInputStream());
		int ch = 0;
		while ((ch = input.read()) != -1) {
			bos.write(ch);
		}
		httpUrlConnection.disconnect();

		byte[] rspData = bos.toByteArray();
		return new String(rspData);		

	}

	public static String post(String url) throws HttpResponseException, ClientProtocolException, IOException {
		HttpPost httpRequest = new HttpPost(url);
		return execute(httpRequest);
	}

	public static String post(String url, InputStream stream, String streamKey) throws HttpResponseException,
			ClientProtocolException, IOException {
		HttpPost httpRequest = new HttpPost(url);
		RequestParams params = new RequestParams();
		params.put(streamKey, stream);
		httpRequest.setEntity(params.getEntity());
		return execute(httpRequest);
	}

	public static String post(String url, String filename, String fileKey) throws HttpResponseException,
			ClientProtocolException, IOException {
		HttpPost httpRequest = new HttpPost(url);
		RequestParams params = new RequestParams();
		params.put(fileKey, new File(filename));
		httpRequest.setEntity(params.getEntity());
		return execute(httpRequest);
	}

	public static String post(String url, RequestParams params) throws HttpResponseException, ClientProtocolException,
			IOException {
		HttpPost httpRequest = new HttpPost(url);
		httpRequest.setEntity(params.getEntity());
		return execute(httpRequest);
	}

	public static String getUrlWithQueryString(String url, RequestParams params) {
		if (params != null) {
			String paramString = params.getParamString();
			if (url.indexOf("?") == -1) {
				url += "?" + paramString;
			} else {
				url += "&" + paramString;
			}
		}

		return url;
	}
}
